package com.ljh.onlinetest.service.impl;

import com.ljh.onlinetest.configuration.property.SystemConfig;
import com.ljh.onlinetest.domain.User;
import com.ljh.onlinetest.service.AuthenticationService;
import com.ljh.onlinetest.service.UserService;
import com.ljh.onlinetest.utils.RsaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author ljh
 * @ClassName AuthenticationServiceImpl.java
 * @createTime 2021年12月30日
 */
@Service
public class AuthenticationServiceImpl implements AuthenticationService {

    private final UserService userService;
    private final SystemConfig systemConfig;

    @Autowired
    public AuthenticationServiceImpl(UserService userService, SystemConfig systemConfig) {
        this.userService = userService;
        this.systemConfig = systemConfig;
    }

    @Override
    public boolean authUser(User user, String username, String password) {
        if (user == null) {
            return false;
        }
        String encodePwd = user.getPassword();
        if (encodePwd == null || encodePwd.length() == 0) {
            return false;
        }
        String pwdDecode = pwdDecode(encodePwd);
        return pwdDecode.equals(password);
    }

    @Override
    public boolean authUser(String username, String password) {
        User user = userService.getUserByUserName(username);
        return authUser(user,username,password);
    }

    @Override
    public String pwdEncode(String password) {
        return RsaUtil.rsaEncode(systemConfig.getPwdKey().getPublicKey(),password);
    }

    @Override
    public String pwdDecode(String password) {
        return RsaUtil.rsaDecode(systemConfig.getPwdKey().getPrivateKey(),password);
    }
}
